package com.cop4331.social;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ScaleDrawable;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @author Daniel Moody
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * View your personal profile
 * 
 */
public class ViewProfileActivity extends Activity {

	final String IP = UserFunctions.getIp();

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewprofilelayout);

		//Buttons
		Button editprofile = (Button) findViewById(R.id.vpeditprofile);
		Button addclasses = (Button) findViewById(R.id.vpaddclass);
		Button imgUp = (Button) findViewById(R.id.vpupdateimg);

		//TextViews
		TextView cnt = (TextView) findViewById(R.id.count);
		TextView Name = (TextView) findViewById(R.id.vpName);
		TextView Phone = (TextView) findViewById(R.id.vpPhone);
		TextView Email = (TextView) findViewById(R.id.vpEmail);
		TextView Major = (TextView) findViewById(R.id.vpMajor);
		RatingBar rating = (RatingBar) findViewById(R.id.rating);

		//ListView
		ListView classlist = (ListView) findViewById(R.id.vpclasslist);

		//ImageView
		ImageView profilepic = (ImageView) findViewById(R.id.profilepic);

		//Get current user info from database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		final String un = user.get("name");
		UserFunctions uf = new UserFunctions();
		JSONObject json = uf.userExists(un);
		JSONObject jsonclasses = uf.retrieveAllCourses(un);

		try {

			// get array of classes
			JSONArray j_classesArray = jsonclasses.names();
			// get how many classes
			int classlistlength = Integer.parseInt(jsonclasses
					.getString("size"));
			int i;

			JSONObject CurrentClass;
			// intialize string for list view later
			String[] ClassesStringArray = new String[classlistlength];
			
			//Set adapter
			classlist.setAdapter(new SimpleAdapter(this, getData(un),
					R.layout.classlist,
					new String[] { "cname", "term", "grade" }, new int[] {
							R.id.course, R.id.term, R.id.grade }));

			//When user presses a listed class
			classlist.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int pos, long id) {

					//Retrieve the current selected item details
					final Map<String, Object> item = (Map<String, Object>) parent
							.getItemAtPosition(pos);

					//Open a dialog
					final Dialog dialog = new Dialog(ViewProfileActivity.this);
					dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog.setContentView(R.layout.alterclassdialog);
					dialog.setCancelable(true);
					
					//Dialog Checkbox
					final CheckBox check = (CheckBox) dialog
							.findViewById(R.id.cbtutor);

					//Dialog Buttons
					Button change = (Button) dialog.findViewById(R.id.b_change);
					Button cancel = (Button) dialog.findViewById(R.id.b_cancel);
					
					//Dialog Spinner
					final Spinner grades = (Spinner) dialog
							.findViewById(R.id.grade);

					ArrayAdapter myAdap = (ArrayAdapter) grades.getAdapter();
					
					//Get spinner item
					int spinnerPosition = myAdap.getPosition(item.get("grade")
							.toString());
					
					//If grade is D or F disable ability to tutor (checkbox)
					if (item.get("grade").toString().compareTo("F") == 0
							|| item.get("grade").toString().compareTo("D") == 0)
						check.setEnabled(false);
					
					//If we are already tutoring, check
					if (Integer.parseInt(item.get("tutoring").toString()) == 1)
						check.setChecked(true);
					else
						check.setChecked(false);

					//Set the spinner to preselected spinnerPosition
					grades.setSelection(spinnerPosition);
					
					//Set functionality to change button
					change.setOnClickListener(new View.OnClickListener() {

						public void onClick(View v) {
							
							String g = grades.getSelectedItem().toString();

							
							if (check.isChecked() == true) {
								
								//If its checked and we cannot tutor, change grade
								//Do not allow tutor
								if (grades.getSelectedItem().toString()
										.compareTo("F") == 0
										|| grades.getSelectedItem().toString()
												.compareTo("D") == 0)
									UserFunctions.updateClass(item.get("id")
											.toString(), "0", g);
								
								//We can tutor, change approriately
								else
									UserFunctions.updateClass(item.get("id")
											.toString(), "1", g);
							}
							//Remove tutor
							else
								UserFunctions.updateClass(item.get("id")
										.toString(), "0", g);

							// Refresh Activity
							Intent log = new Intent(getApplicationContext(),
									ViewProfileActivity.class);

							dialog.dismiss();
							startActivity(log);
							finish();
						}
					});
					
					//Dismiss dialog on cancel
					cancel.setOnClickListener(new View.OnClickListener() {

						public void onClick(View v) {
							dialog.dismiss();
						}
					});

					dialog.setCanceledOnTouchOutside(true);
					dialog.show();

				}
			});

			// get user info
			JSONObject j_user = json.getJSONObject("user");

			// set user info
			String temp = j_user.getString("full");
			Name.setText(temp);
			
			// get phone
			temp = j_user.getString("phone");
			Phone.setText(temp);

			// get email
			temp = j_user.getString("email");
			Email.setText(temp);

			// get major
			temp = j_user.getString("major");
			Major.setText(temp);

			// get rating
			rating.setRating((float) Double.parseDouble(j_user
					.getString("rating")));
			cnt.setText("Out of " + j_user.getString("numRatings")
					+ " rating(s)");

			// get image location from database
			String imagename = j_user.getString("img");

			String URLstring = IP + "profilepictures/" + imagename;

			// method to get the picture
			// method to get the actual picture form the database
			Drawable drawable = grabImageFromUrl(URLstring);

			// method resizes the picture ***<----------- this seems a slow
			// method, there might be better ways
			// drawable = resize(drawable);

			// sets the picture to the image
			profilepic.setImageDrawable(drawable);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Goto editprofile activity
		editprofile.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						EditProfileActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		//Goto add class activity
		addclasses.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						AddclassActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		//Goto imageupload activity
		imgUp.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Bundle username for ImageuploadActivity slide
				Bundle b = new Bundle();
				b.putString("username", un);
				b.putString("from", "1");

				Intent sa = new Intent(getApplicationContext(),
						ImageuploadActivity.class);
				sa.putExtras(b);

				startActivity(sa);
				finish();

			}
		});
		
		//Title bar buttons
		ImageButton about, home, message;

		about = (ImageButton) findViewById(R.id.b_about);
		home = (ImageButton) findViewById(R.id.b_home);
		message = (ImageButton) findViewById(R.id.b_message);
		
		//Check for new messages
		JSONObject j_mess = uf.retreiveMessages(un, "new");

		try {
			if (Integer.parseInt(j_mess.getString("size")) > 0) {
				message.setVisibility(View.VISIBLE);
			} else
				message.setVisibility(View.GONE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	
		//Show app info
		about.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(ViewProfileActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("CramSessions v 1.0 2012");
				dialog.setCancelable(true);

				// Create and show a dialog to help the user with this specific
				// field
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("CramSessions was created by:\n\n-Matt Szoke\n-Daniel Moody\n-Jeovanny Alvarez\n-Kia Manoochehri\n-Rj Anderson\n-Doug Wagner");
				text.setGravity(Gravity.LEFT);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});

		//Return to dashboard on press
		home.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		//Goto inbox on press, only if new messages exist
		message.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(sa);
				finish();

			}
		});

	}

	private Drawable grabImageFromUrl(String url) throws Exception {
		return Drawable.createFromStream(
				(InputStream) new URL(url).getContent(), "src");
	}

	private Drawable resize(Drawable image) {
		Bitmap d = ((BitmapDrawable) image).getBitmap();
		Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 300, 400, false);
		return new BitmapDrawable(bitmapOrig);
	}

	// -----------------------------------------------
	// GETDATA
	// Retreives and returns list of classes from the database
	// -----------------------------------------------
	private List<Map<String, Object>> getData(String username) throws Exception {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // Used
																				// to
																				// store
																				// the
																				// available
																				// tutors
																				// from
																				// Database

		// Retreive new messages
		UserFunctions uf = new UserFunctions();
		JSONObject jsonclasses = uf.retrieveAllCourses(username);

		// Stores size of the list returned from Database
		int size;

		try {
			size = Integer.parseInt(jsonclasses.getString("size"));
			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_class = jsonclasses.getJSONObject("" + i);

					// Place each object in the HashMap
					if (Integer.parseInt(json_class.getString("tutoring")) == 1)
						map.put("cname", "*" + json_class.getString("cname"));
					else
						map.put("cname", json_class.getString("cname"));
					map.put("term", json_class.getString("term"));
					map.put("grade", json_class.getString("grade"));
					map.put("id", json_class.getString("id"));
					map.put("tutoring", json_class.getString("tutoring"));

					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return list;
	}
}
